﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using ScrewTurnHelper.Syntax;

namespace ScrewTurnHelper
{
	public partial class MainPage
	{
		public MainPage()
		{
			InitializeComponent();
		}

		private void tabToTableButtonClick(object sender, RoutedEventArgs e)
		{
			var data = TabDelimited.Parse(input.Text);
			MakeTable(data);
		}

		private void MakeTable(DataTable data)
		{
			var wiki = new StringBuilder();

			wiki.AppendLine(@"{| border=""1"" cellspacing=""0"" cellpadding=""3""");


			bool first = true;
			foreach(var row in data.Rows)
			{
				if (!first)
					wiki.AppendLine("|-");
				first = false;
				AddRow(wiki, row);
			}

			wiki.AppendLine(@"|}");

			output.Text = wiki.ToString();
			output.SelectAll();
			output.Focus();
		}

		private static void AddRow(StringBuilder wiki, IEnumerable<string> row)
		{
			bool first = true;
			foreach(var col in row)
			{
				if (!first)
					wiki.Append("|");
				first = false;
				if (string.IsNullOrEmpty(col))
					wiki.Append("| &nbsp; "); 
				else
					wiki.Append("| " + col + " "); 
			}
			wiki.AppendLine("");
		}

		private void csvToTableButtonClick(object sender, RoutedEventArgs e)
		{
			var data = CsvParser.Parse(input.Text);
			MakeTable(data);
		}

		private void SetOutput(SourceFormat f)
		{
			var s = f.FormatCode(input.Text);
			s = s.Replace("--", "<nowiki>--</nowiki>");
			s = s.Replace("[", "<nowiki>[</nowiki>");
			s = s.Replace("]", "<nowiki>]</nowiki>");
			output.Text = s;

			output.SelectAll();
			output.Focus();
		}

		private void pascalHiliteClick(object sender, RoutedEventArgs e)
		{
			SetOutput(new DelphiFormat());
		}

		private void csharpHiliteClick(object sender, RoutedEventArgs e)
		{
			SetOutput(new CSharpFormat());
		}

		private void tsqlHiliteClick(object sender, RoutedEventArgs e)
		{
			SetOutput(new TsqlFormat());
		}
	}
}
